package cn.codergege.kotlinclass.ktdelegate

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class Example {
    val someName by NameDelegate()
    val anotherName by NameDelegate()
}

class NameDelegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): Any {
        return property.name
    }
}

class Example2 {
    var someName by NameDelegate2()
}

class NameDelegate2 {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return property.name
    }
    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Any?) {
        println("Setting $value")
    }
}

class Example3 {
    var someName by NameDelegate3()
}

class NameDelegate3: ReadWriteProperty<Example3, String> {
    override fun getValue(thisRef: Example3, property: KProperty<*>): String {
        return property.name
    }

    override fun setValue(thisRef: Example3, property: KProperty<*>, value: String) {
        println("${property.name} setting $value")
    }
}

fun main(args: Array<String>) {
    val ex = Example()
    println("${ex.someName} -- ${ex.anotherName}") // 打印 someName -- anotherName
    val ex2 = Example2()
    ex2.someName = "xxx" // 打印 Setting xxx
    println(ex2.someName) // 打印 someName
    val ex3 = Example3()
    println(ex3.someName)
}
